<?php

declare(strict_types=1);

namespace App\Model;


use App\Dao\CityIpDao;

/**
 * @property int $id
 * @property string $ip_start 开始ip
 * @property string $ip_end 结束ip
 * @property string $iplong_start
 * @property string $iplong_end
 * @property string $channel
 * @property string $city 城市
 * @property string $remark 备注信息
 * @property int $status 1开启 0关闭
 * @property string $create_time 添加时间
 */
class AuditIpSegment extends Model
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'tb_audit_ip_segment';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = [];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'status' => 'integer'];


    /**
     * Note - 判断是否为审核ip
     * DateTime 2024/7/29 16:06
     * User Admin
     * @param string $ip
     * @param $channel
     * @return bool
     */
    public function isAuditIp(string $ip, $channel)
    {
        $ipLong = ip2long($ip);
        $ipcache = CityIpDao::getInstance()->getProvinceCity($ip);
        $province = $ipcache["province"] ?: "";
        $city = $ipcache['city'] ?: '';
        $rs = self::query()->where('status', 1)->where(function ($query) use ($ipLong) {
            $query->where('iplong_start', '<=', $ipLong)->orWhere('iplong_end', '>=', $ipLong);
        })->orWhere(function ($query) use ($province, $city) {
            $query->whereRaw("FIND_IN_SET(?, city)", [$province])->orWhereRaw("FIND_IN_SET(?, city)", [$city]);
        })->where(function ($query) use ($channel) {
            $query->where('channel', $channel)->orWhere('channel', '');
        })->first();
        if ($rs) {
            return true;
        }
        return false;

    }
}
